<template>
  <div v-loading.fullscreen.lock="loading" element-loading-text="Loading...">
    <Notfound v-if="!loading" :description="description"></Notfound>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import routes from '../router/routes'
import { getDeptTree, getUser } from '../api/common'
import user, { UserRole } from '../store/user'
import Notfound from './notfound.vue'
import deptTree from '../store/deptTree'

const router = useRouter()
const route = useRoute()

const loading = ref(false)

const description = ref()

function setChildren(routes: RouteRecordRaw[], roles: UserRole[], parent: RouteRecordRaw | null) {
  routes.forEach((item) => {
    item.meta!.auth = true
    item.meta!.menu = true
    item.name = item.path.replace('/', '').replace(/\/+/g, '_')
    if (item.children?.length) {
      item.children = setChildren(item.children, roles, item)
    }
  })

  return parent
    ? routes
    : routes
        .filter((item) => !item.children || item.children.length)
        .filter((item) => {
          const ros = item.meta!.roles as UserRole[] | undefined
          return (
            ros &&
            ros.some((role) => {
              return roles.includes(role)
            })
          )
        })
}

if (user.token && !user.menu.length) {
  loading.value = true
  setTimeout(() => {
    getUser<{
      roles: UserRole[]
      username: string
      sysUser: {
        dept: {
          deptName: string
        }
      }
    }>()
      .then(({ data }) => {
        //加载用户权限路由
        const children = setChildren(routes, data.roles, null)

        //设置用户信息
        user.setRoles(data.roles)
        user.setUserName(data.username)
        user.setMenu(children)
        user.setDeptName(data.sysUser.dept.deptName)

        router.addRoute({
          path: '/auth',
          name: 'auth',
          redirect: { path: children[0].path },
          meta: { title: '', auth: true },
          component: () => import('./index.vue'),
          children
        })

        //获取相关部门
        getDeptTree<DeptTree>().then(({ data: result }) => {
          deptTree.setDeptTree(result)
        })

        router.replace({ path: route.path }).then(() => {
          loading.value = false
        })
      })
      .catch(({ msg }) => {
        description.value = msg
        loading.value = false
      })
  }, 1000)
}
</script>
